package com.hzqy.commons.utils;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

public class PostUtil {
	private static final Log LOG = LogFactory.getLog(PostUtil.class);

	public static Map<String, String> post(String urlStr) {
		LOG.debug(urlStr);
		HttpURLConnection con = null;
		Map<String, String> map = new HashMap<String, String>();
		String result = "";
		String success = "0";
		InputStreamReader isr = null;
		InputStream is = null;
		try {// 获取HttpURLConnection连接对象
			URL url = new URL(urlStr);
			con = (HttpURLConnection) url.openConnection();
			// 设置连接属性
			con.setDoOutput(true);
			con.setRequestMethod("POST");
			con.setRequestProperty("version", "1.0");
			con.setRequestProperty("Content-Type", "text/xml");
			con.setRequestProperty("Pragma", "no-cache");
			con.setRequestProperty("Cache-Control", "no-cache");
			con.setConnectTimeout(10000);
			con.setReadTimeout(10000);
			is = con.getInputStream();

			int respCode = con.getResponseCode();
			isr=new InputStreamReader(con.getInputStream(),"UTF-8");
			if (respCode == 200) {
				success = "1";
				BufferedReader br = new BufferedReader(isr);
				String line = "";
				for (line = br.readLine(); line != null; line = br.readLine()) {
					result+=line;
				}
			}else{
				success = "2";
				result = "response_status: " + respCode;
			}
		} catch (Exception e) {
			success = "2";
			//result = e.getMessage();


		}finally {
			if(con != null)
				con.disconnect();
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
				}
			}
			if (isr != null) {
				try {
					isr.close();
				} catch (IOException e) {
				}
			}
		}
		map.put("result", result);
		map.put("success", success);
		return map;
	}
}
